package cn.exrick.xboot.modules.workovertime.service.serviceimpl;

import cn.exrick.xboot.flow.entity.FlowHistory;
import cn.exrick.xboot.flow.entity.FlowInstanceinfo;
import cn.exrick.xboot.flow.entity.FlowTaskInstance;
import cn.exrick.xboot.flow.mapper.FlowHistoryMapper;
import cn.exrick.xboot.flow.mapper.FlowInstanceinfoMapper;
import cn.exrick.xboot.flow.mapper.FlowTaskHandlerMapper;
import cn.exrick.xboot.flow.service.IFlowInstanceinfoService;
import cn.exrick.xboot.flow.service.IFlowTaskInstanceService;
import cn.exrick.xboot.modules.assessment.entity.HkAssessmentScore;
import cn.exrick.xboot.modules.assessment.vo.HkAssessmentRecordVo;
import cn.exrick.xboot.modules.assessment.vo.HkassessmentScoreAndRecordVo;
import cn.exrick.xboot.modules.base.utils.DateUtils;
import cn.exrick.xboot.modules.content.dao.HontUserDao;
import cn.exrick.xboot.modules.content.dao.mapper.HontUserMapper;
import cn.exrick.xboot.modules.content.entity.HontUser;
import cn.exrick.xboot.modules.workovertime.VO.HkOvertimeByPageVo;
import cn.exrick.xboot.modules.workovertime.VO.HkOvertimeInfoNameAndUserNickVo;
import cn.exrick.xboot.modules.workovertime.VO.HkOvertimeSummarizingByMonthVo;
import cn.exrick.xboot.modules.workovertime.VO.HkassessmentOvertimeAndRecordVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.exrick.xboot.modules.workovertime.entity.HkOvertimeDetail;
import cn.exrick.xboot.modules.workovertime.mapper.HkOvertimeDetailMapper;
import cn.exrick.xboot.modules.workovertime.mapper.HkOvertimeInfoMapper;
import cn.exrick.xboot.modules.workovertime.mapper.HkOvertimeUserMapper;
import cn.exrick.xboot.modules.workovertime.service.IHkOvertimeDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import javax.persistence.criteria.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hml
 * @since 2023-08-31
 */
@Service
@Transactional
@Slf4j
public class HkOvertimeDetailServiceImpl extends ServiceImpl<HkOvertimeDetailMapper, HkOvertimeDetail> implements IHkOvertimeDetailService {


    @Autowired
    private HkOvertimeDetailMapper hkOvertimeDetailMapper;
    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    public IFlowInstanceinfoService flowInstanceinfoService;
    @Autowired
    public IFlowTaskInstanceService iFlowTaskInstanceService;
    @Autowired
    private FlowInstanceinfoMapper flowInstanceinfoMapper;
    @Autowired
    private FlowHistoryMapper flowHistoryMapper;
    @Autowired
    private FlowTaskHandlerMapper flowTaskHandlerMapper;
    @Autowired
    private IFlowTaskInstanceService flowTaskInstanceService;
    @Autowired
    private HontUserDao hontUserDao;


    @Override
    public IPage<HkOvertimeDetail> selectPage(Page<HkOvertimeDetail> page, HkOvertimeDetail hkOvertimeDetail) {
        QueryWrapper<HkOvertimeDetail> query = Wrappers.query();
        QueryWrapper<HkOvertimeDetail> entityWrapper = getEntityWrapper(query, hkOvertimeDetail);
        return hkOvertimeDetailMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<HkOvertimeDetail> selectList(HkOvertimeDetail hkOvertimeDetail) {
        QueryWrapper<HkOvertimeDetail> query = Wrappers.query();
        QueryWrapper<HkOvertimeDetail> entityWrapper = getEntityWrapper(query, hkOvertimeDetail);
        return hkOvertimeDetailMapper.selectList(entityWrapper);
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HkOvertimeDetail> getEntityWrapper(QueryWrapper<HkOvertimeDetail> entityWrapper, HkOvertimeDetail hkOvertimeDetail) {
        //条件拼接
        if (StringUtils.isNotBlank(hkOvertimeDetail.getCreateBy())) {
            entityWrapper.like(HkOvertimeDetail.CREATE_BY, hkOvertimeDetail.getCreateBy());
        }
        if (StringUtils.isNotBlank(hkOvertimeDetail.getUpdateBy())) {
            entityWrapper.like(HkOvertimeDetail.UPDATE_BY, hkOvertimeDetail.getUpdateBy());
        }
        if (StringUtils.isNotBlank(hkOvertimeDetail.getAssessmentStatus())) {
            entityWrapper.like(HkOvertimeDetail.ASSESSMENT_STATUS, hkOvertimeDetail.getAssessmentStatus());
        }
        if (StringUtils.isNotBlank(hkOvertimeDetail.getCause())) {
            entityWrapper.like(HkOvertimeDetail.CAUSE, hkOvertimeDetail.getCause());
        }
        if (StringUtils.isNotBlank(hkOvertimeDetail.getApprovalUserId())) {
            entityWrapper.like(HkOvertimeDetail.APPROVAL_USER_ID, hkOvertimeDetail.getApprovalUserId());
        }
        if (StringUtils.isNotBlank(hkOvertimeDetail.getApprovalName())) {
            entityWrapper.like(HkOvertimeDetail.APPROVAL_NAME, hkOvertimeDetail.getApprovalName());
        }
        if (StringUtils.isNotBlank(hkOvertimeDetail.getProcessInstanceId())) {
            entityWrapper.like(HkOvertimeDetail.PROCESS_INSTANCE_ID, hkOvertimeDetail.getProcessInstanceId());
        }
        if (StringUtils.isNotBlank(hkOvertimeDetail.getIndexComment())) {
            entityWrapper.like(HkOvertimeDetail.INDEX_COMMENT, hkOvertimeDetail.getIndexComment());
        }
        return entityWrapper;
    }

    @Override
    public HkassessmentOvertimeAndRecordVo getHkOvertimeDetial(String processInstanceId) {
        QueryWrapper<HkOvertimeDetail> detailQueryWrapper = Wrappers.query();
        detailQueryWrapper.lambda().eq(HkOvertimeDetail::getProcessInstanceId,processInstanceId);
        List<HkOvertimeDetail> hkOvertimeDetails = hkOvertimeDetailMapper.selectList(detailQueryWrapper);
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<HkAssessmentRecordVo> records=new ArrayList<HkAssessmentRecordVo>();
        FlowInstanceinfo flowInstanceinfo = flowInstanceinfoMapper.selectById(processInstanceId);
        QueryWrapper<FlowHistory> query = Wrappers.query();
        query.lambda().eq(FlowHistory::getFlowInstanceId,processInstanceId);
        List<FlowHistory> flowHistories = flowHistoryMapper.selectList(query);
        if (flowInstanceinfo != null){
            HkAssessmentRecordVo record=new HkAssessmentRecordVo();
            record.setTime(flowInstanceinfo.getFlowCreateTime().format(fmt));
            record.setNickName(flowInstanceinfo.getFlowHandler());
            record.setAssessmentStatus("提交申请发起人");
            records.add(record);
        }
        if (flowHistories.size() > 0){
            for (int i = 0; i < flowHistories.size(); i++) {
                HkAssessmentRecordVo record=new HkAssessmentRecordVo();
                record.setTime(LocalDateTime.now().format(fmt));

                if (flowHistories.get(i).getTaskEndTime() == null){
                    record.setAssessmentStatus("未审核");
                    FlowTaskInstance flowTaskInstanceByFlowInstance = flowTaskInstanceService.getFlowTaskInstanceByFlowInstance(flowHistories.get(i).getFlowInstanceId());
                    List<String> approvalUsers = flowTaskHandlerMapper.getApprovalUsers(flowTaskInstanceByFlowInstance.getId());
                    if (approvalUsers.size() > 0){
                        String join = Joiner.on(",").join(approvalUsers);
                        record.setNickName(join);
                    }
                    Map<String, Object> dateTimePoor = DateUtils.getDateTimePoor(LocalDateTime.now(), flowHistories.get(i).getTaskCreateTime());
                    record.setElapsedTime(dateTimePoor.get("elapsedTime").toString());
                    record.setElapsedTimeStatus(dateTimePoor.get("elapsedTimeStatus").toString());
                }else {
                    record.setAssessmentStatus(flowHistories.get(i).getAssessmentStatus());
                    record.setTime(flowHistories.get(i).getTaskEndTime().format(fmt));
                    Map<String, Object> dateTimePoor = DateUtils.getDateTimePoor(flowHistories.get(i).getTaskEndTime(), flowHistories.get(i).getTaskCreateTime());
                    record.setElapsedTime(dateTimePoor.get("elapsedTime").toString());
                    record.setElapsedTimeStatus(dateTimePoor.get("elapsedTimeStatus").toString());
                    Optional<HontUser> byId = hontUserDao.findById(flowHistories.get(i).getTaskHandler());
                    record.setNickName( byId.get().getNickName());

                }

                records.add(record);
            }
        }
        Iterator<HkOvertimeDetail> iterator = hkOvertimeDetails.iterator();
        while (iterator.hasNext()){
            HkOvertimeDetail next = iterator.next();
            if(!next.getIsCurrentAssessment().equals("1")){
                iterator.remove();
            }
        }
        HkassessmentOvertimeAndRecordVo vo=new HkassessmentOvertimeAndRecordVo();
        vo.setHkAssessmentRecordVos(records);
        vo.setHkOvertimeDetails(hkOvertimeDetails);
        return vo;
    }

    @Override
    public List<HkOvertimeInfoNameAndUserNickVo> getHkOvertimeInfoAndUserNickNameByOutput(HkOvertimeByPageVo hkOvertimeByPageVo) {
        return hkOvertimeDetailMapper.getHkOvertimeInfoAndUserNickNameByOutput(hkOvertimeByPageVo);
    }

    @Override
    public List<HkOvertimeInfoNameAndUserNickVo> getHkOvertimeSummarizingAndUserNickName(HkOvertimeByPageVo hkOvertimeByPageVo) {
        return hkOvertimeDetailMapper.getHkOvertimeSummarizingAndUserNickName(hkOvertimeByPageVo);
    }

    @Override
    public List<HkOvertimeSummarizingByMonthVo> getHkOvertimeSummarizingByMonth(HkOvertimeByPageVo hkOvertimeByPageVo){
        return hkOvertimeDetailMapper.getHkOvertimeSummarizingByMonth(hkOvertimeByPageVo);
    }

}
